var App = getApp();
var ApiUrl = App.data.ApiUrl;
var Common = require('../../../utils/common.js');
Page({
  data: {
    showState: 1,
    if_showpsd: true,

    SMCTime: 60,
    SMCTimes: true,
    SMCode_Lock: false,
    SMCode_Msg: '获取验证码',

    smsValue: '',
  },
  onLoad: function (options) {
    var page = this;
    Common.w_widths(page);
    page.getSellerInfo();
    var consultant_sn = wx.getStorageSync("consultant_sn"),
      openid = wx.getStorageSync('openid'),
      token = wx.getStorageSync("token");
    page.setData({
      consultant_sn: consultant_sn,
      openid: openid,
      token: token
    })
    wx.setNavigationBarTitle({
      title: '卖酒码绑定'
    })
  },

  imageLoad: function (e) {
    var page = this;
    var viewHeight = Common.imageLoadAn(e, this.data.w_width);
    viewHeight = viewHeight.toFixed(0);
    page.setData({
      imageSize: viewHeight
    })
  },

  /**
   * @description 获取配置信息
   * @method getSellerInfo
   * @returns void
   *
   */
  getSellerInfo() {
    var page = this;
    Common.my_request({
      url: 'AppMaster/ConsultantApply/applyFormSetting',
      success: function (res) {
        console.log(res)
        if (res.data.result == 0) {
          var data = res.data.data;
          page.setData({
            deploy: data
          })
        }
      }
    })
  },

  /**
   * @description 检测手机号绑定情况
   * @method testPhone
   * @returns void
   *
   */
  testPhone() {
    var page = this;
    var phone = page.data.phone;

    var myreg = /^0?1\d{10}$/;
    if (!phone) {
      Common.Alert('提示', '请输入手机号码');
      return false;
    } else if (!myreg.test(phone)) {
      Common.Alert('提示', '请输入正确的手机号码');
      return false;
    } else {
      Common.my_request({
        url: 'AppMaster/SellingCode/preLogin',
        data: {
          phone: phone
        },
        success:  (res) => {
          if (res.data.result == 0) {//1.2已有账号，但未绑定
            page.setData({
              showState: 2,
              tips: res.data.message
            })
          } else if (res.data.result == 302) {/**pass */
            if (res.data.redirect == "consultant/apply") {//1.1没有账号，没有绑定
              page.setData({
                showState: 4,
                tips: res.data.message
              })
            } else if (res.data.redirect == "sellingCode/tips") {
              //1.3已有账号，手机号已经注册为其他销售商的顾问
              //1.4手机号已经绑定当前销售商的二维码
              page.setData({
                showState: 3,
                tips: res.data.message
              })
              if (res.data.sellingServer) {
                var id = res.data.sellingServer;
                page.changeConsulant(id);
              }
            }
          } else {
            Common.Alert('提示', res.data.message);
          }

        }
      })
    }
  },

  /**
   * @description 切换顾问
   * @method changeConsulant
   * @returns void
   *
   */
  changeConsulant: function (id) {
    Common.my_request({
      url: 'AppMaster/Account/selectNewConsultant',
      data: {
        salesman_id: id
      },
      success: function (res) {
        if (res.data.result == 0) {
          Common.when_user_change_clear_the_storage();
        } else {
          wx.showToast({
            title: res.data.message,
            image: '/pages/imges/fail.png',
            duration: 2000
          })
        }
      }
    });
  },

  /**
   * @description 立即申请
   * @method applicate
   * @returns void
   *
   */
  applicate() {
    var page = this,
      name = page.data.name,
      smsValue = page.data.smsValue;
    console.log(smsValue)
    if (!name) {
      Common.Alert('提示', "请输入姓名");
      return false;
    }
    if (!smsValue) {
      Common.Alert('提示', "请输入验证码");
      return false;
    }
    wx.request({
      url: ApiUrl + 'AppMaster/ConsultantApply/apply',
      data: {
        phone: page.data.phone,
        realName: page.data.name,
        sn: page.data.consultant_sn,
        smsCode: page.data.smsValue,
        token: page.data.token
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.result == 0) {
          wx.navigateTo({
            url: '/pages/join/result/result?state=1'
          })
        } else {
          Common.Alert('提示', res.data.message);
        }
      }
    })
  },

  /**
   * @description 1.2输入密码绑定
   * @method bindAccount
   * @returns void
   *
   */
  bindAccount: function (e) {
    var page = this,
      userName = page.data.phone,
      passWord = page.data.normalPwD,
      openid = page.data.openid;

    if (!passWord) {
      Common.Alert('提示', '请输入密码');
      return false;
    }
    Common.my_request({
      url: 'AppMaster/Login/login',
      data: {
        userName: userName,
        password: passWord,
        openid: openid,
      },
      success: function (res) {
        if (res.data.result == 0) {
          var login_token = res.data.token;
          page.bindFunction(login_token);

        } else {
          Common.Alert('提示', res.data.msg);
        }
      }
    });
  },

  /**
   * @description 验证码登录
   * @method SMS_login
   * @returns void
   *
   */
  SMS_login() {
    var page = this;
    Common.my_request({
      url: '/AppMaster/Login/checkMessageCodeLogin',
      data: {
        phone: page.data.phone,
        code: page.data.smsValue,
      },
      success: function (res) {
        if (res.data.result == 0) {
          var login_token = res.data.data.token;
          page.bindFunction(login_token);
        } else {
          wx.hideLoading();
          page.setData({
            SMCTime: 60,
            SMCode_Lock: false,
            SMCode_Msg: '获取验证码',
            SMCTimes: true,
          })
          Common.Alert('提示', res.data.message);
        }
      }
    })
  },

  /**
   * @description 提交绑定卖酒码请求
   * @method bindFunction
   * @returns void
   *
   */
  bindFunction(login_token) {
    var page = this;
    wx.request({
      url: ApiUrl + 'AppMaster/SellingCode/doBindWithServer',
      data: {
        sn: page.data.consultant_sn,
        token: login_token
      },
      method: 'post',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      success: function (res) {
        console.log(res);
        if (res.data.result == 0) {
          wx.navigateTo({
            url: '/pages/join/result/result?state=2'
          })
        } else {
          Common.Alert('提示', res.data.message, function () {
            page.toIndex();
          });
        }
      }
    })
  },

  /**
   * @description 获取手机号验证码
   * @method getSMS
   * @returns void
   *
   */
  getSMS: function (e) {
    var page = this;
    var phone = page.data.phone;

    page.setData({
      SMCode_Lock: true
    });

    console.log(phone)
    // 获取验证码
    wx.request({
      url: ApiUrl + '/AppMaster/Login/bindPhoneSendMessageCode',
      data: {
        phone: phone
      },
      header: {
        'content-type': 'json'
      },
      success: function (res) {
        if (res.data.result == 0) {
          wx.showToast({
            title: '验证码已发送',
            icon: 'success',
            duration: 2000
          })
          // 倒计时显示
          page.SMCode_Msg();
        } else {
          page.setData({
            SMCTime: 60,
            SMCode_Lock: false,
            SMCode_Msg: '获取验证码'
          })
          Common.Alert('错误提示', res.data.message);
        }
      }
    })

  },

  SMCode_Msg: function () {
    console.log('SMCode_Msg');
    var page = this;
    var SMCTimers;
    var SMCTime = page.data.SMCTime;
    var SMCode_Msg = page.data.SMCode_Msg;
    var SMCode_Lock = page.data.SMCode_Lock;
    if (SMCTime > 1) {
      SMCTime--;
      SMCode_Msg = '重新获取(' + SMCTime + ')';
      page.setData({
        SMCTime: SMCTime,
        SMCode_Msg: SMCode_Msg,
        SMCTimes: false,
      })
      // 定时器执行
      SMCTimers = setTimeout(function () {
        page.SMCode_Msg();
      }, 1000);

    } else {
      clearTimeout(SMCTimers);
      page.setData({
        SMCTime: 60,
        SMCode_Lock: false,
        SMCode_Msg: '获取验证码',
        SMCTimes: true,
      })
    }
  },

  /**
   * @description 去首页
   * @method toIndex
   * @returns void
   *
   */
  toIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    })
  },

  /**
   * @description 手机号验证码登录
   * @method hidepsd
   * @returns void
   *
   */
  hidepsd() {
    this.setData({
      if_showpsd: false
    })
  },

  showpsd() {
    this.setData({
      if_showpsd: true
    })
  },

  //更新手机号输入框的值
  updatePhone: function (e) {
    this.setData({
      phone: e.detail.value
    })
  },

  //更新用户姓名
  changeName: function (e) {
    this.setData({
      name: e.detail.value
    })
  },

  //更新验证码
  changeSMS: function (e) {
    this.setData({
      smsValue: e.detail.value
    })
  },

  //更新密码
  updatePwd: function (e) {
    this.setData({
      normalPwD: e.detail.value
    })
  },

  onPullDownRefresh: function () {
    wx.stopPullDownRefresh()
  },
  selectNum (e) {

  },
  confirmNum(e){

  },
  closeNum (e){
    
  }
})